package com.eric.similarity.pipe;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.eric.similarity.Main.Config;

public class FilePipe<K> implements Pipe<K>{
	String path;
	HashMap<Entry<K,K>,Entry<K,K>> FileMap = new HashMap<Entry<K,K>,Entry<K,K>>();

	public FilePipe (String path) {
		this.path = path;
		MapOfPipe ();
	}
	
	public FilePipe () {
	}
	
	public HashMap<Entry<K,K>,Entry<K,K>> getMap () {
		return FileMap;
	}
	
	public FilePipe<K> getPipe () {
		return this;
	}
	
	/**
	 * 计算path下各文件到两两相似值
	 * 
	 * @param path
	 *            输入目录位置
	 * @return void
	 */
	@SuppressWarnings("unchecked")
	public void MapOfPipe () {
		File input = new File(path);
		File[] files = input.listFiles();
		
		for (int i=0;i<files.length;i++) {
			for (int j=0;j<files.length && j!=i;j++) {
				try {
					FileMap.put(
								new AbstractMap.SimpleEntry<K,K>(
								(K)
									files[i].getName(), 
								(K)
									files[j].getName()
								),					
								new AbstractMap.SimpleEntry<K,K>(
								(K)
									File2StringBuilder(files[i]).toString(),
								(K) 
									File2StringBuilder(files[j]).toString())
								);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public StringBuilder File2StringBuilder (File file) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(file));
		StringBuilder sb = new StringBuilder();
		String line;
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
		br.close();
		return sb;
	}

	@Override
	public void text() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void write(Map<K,K> SimMap) {
		File file = new File(Config.OUTPUT_PATH);

		if (!file.exists()) {
			new File(file.getParent()).mkdir();
		}

		PrintWriter pw = null;
		try {
			pw = new PrintWriter(file);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		for (Entry<K, K> e : SimMap.entrySet()) {
			pw.println(e);
		}
		pw.flush();
		pw.close();
	}
}
